import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import { actionCreators } from './store';

import Container from '@icedesign/container';
import { Button, Dialog, Input } from '@alifd/next';
import {
  FormBinderWrapper,
  FormBinder,
  FormError,
} from '@icedesign/form-binder';

//格式化日期
Date.prototype.Format = function (fmt) {
  var o = {
    "y+": this.getFullYear(),
    "M+": this.getMonth() + 1,                 //月份
    "d+": this.getDate(),                    //日
    "h+": this.getHours(),                   //小时
    "m+": this.getMinutes(),                 //分
    "s+": this.getSeconds(),                 //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S+": this.getMilliseconds()             //毫秒
  };
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)){
      if(k == "y+"){
        fmt = fmt.replace(RegExp.$1, ("" + o[k]).substr(4 - RegExp.$1.length));
      }
      else if(k=="S+"){
        var lens = RegExp.$1.length;
        lens = lens==1?3:lens;
        fmt = fmt.replace(RegExp.$1, ("00" + o[k]).substr(("" + o[k]).length - 1,lens));
      }
      else{
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
      }
    }
  }
  return fmt;
}

class AccountPanel extends PureComponent {
  static displayName = 'AccountPanel';
  // constructor(props) {
  //   super(props);
  //   this.state = {
  //     open: false,
  //     value: {
  //       nickName: '爱你的源儿',
  //       realName: '张山',
  //       email: '2329082643@qq.com',
  //       phoneNum: '17782089823',
  //       personId: '500331100610120988',
  //       balance: '1.9',
  //       accountAdress: 'adsadascde12313',
  //       createTime: '2019.01.01',
  //       experience: '800',
  //     },
  //   };
  // }

  // handleOpenEditPanel = () => {
  //   this.setState({
  //     open: true
  //   });
  // };

  // handleCloseEditPanel = () => {
  //   this.setState({
  //     open: false
  //   });
  // };

  // formChange = (value) => {
  //   // 说明：
  //   // 1. 表单双向通行，所有表单的相应数据都会同步更新value
  //   // 2. 这里 setState 只是喂了实时展示当前表单数据的演示使用
  //   console.log(value);
  //   this.setState({ value });
  // };

  // 隐藏部分姓名/电话号码/身份证号/钱包地址
  hidden = (str, frontLen, endLen) => {
    let len = str.length - frontLen - endLen;
    let hide = '';
    for(let i=0; i<len; i++) {
      hide += '*';
    }
    return str.substring(0, frontLen) + hide + str.substring(str.length - endLen);
  };

  render() {
    const { settingsData, dialogVisible } = this.props;
    let realName = settingsData.realName;
    let phone = settingsData.phone;
    let idNumber = settingsData.idNumber;
    let walletAddress = settingsData.walletAddress;
    let createTime = new Date(settingsData.createTime);

    return (
      <Container>
        <div style={styles.header}>
          <h2 style={styles.title}>账号信息</h2>
          <div>
            <Button onClick={this.props.handleOpenEditPanel} type="primary" style={{ backgroundColor: '#336666' }}>
              修改
            </Button>
          </div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>用户昵称</div>
          <div style={styles.infoDetail}>{settingsData.username}</div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>真实姓名</div>
          <div style={styles.infoDetail}>{ realName ? this.hidden(realName, 0, realName.length-1) : '未实名认证'}</div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>账号头像</div>
          <div style={styles.infoDetail}>
            <img
              src={require('./images/avatar.jpg')}
              style={{ width: 120 }}
              alt=""
            />
          </div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>手机号码</div>
          <div style={styles.infoDetail}>{phone ? this.hidden(phone, 3, 4) : '无'}</div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>身份证号</div>
          <div style={styles.infoDetail}>{idNumber ? this.hidden(idNumber, 3, 4) : '未实名认证'}</div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>经验值</div>
          <div style={styles.infoDetail}>{settingsData.userExperience}分</div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>钱包地址</div>
          <div style={styles.infoDetail}>{walletAddress ? this.hidden(walletAddress, 3, 4) : '无'}</div>
        </div>
        <div style={styles.infoRow}>
          <div style={styles.infoLabel}>加入时间</div>
          <div style={styles.infoDetail}>{createTime.Format("yyyy年MM月dd日 hh:mm:ss")}</div>
        </div>
        {/** dialog start */}
        <Dialog
          visible={dialogVisible}
          onOk={() => this.props.submitEdit(settingsData)}
          onClose={this.props.handleCloseEditPanel}
          onCancel={this.props.handleCloseEditPanel}
          title="修改账户信息"
        >
          <FormBinderWrapper
            value={settingsData}
          >
            <div>
              <div style={styles.formItem}>
                <span style={styles.formItemLabel}>昵称：</span>
                <FormBinder name="username" message="请输入正确的昵称" >
                  <Input placeholder={settingsData.username} />
                </FormBinder>
                <FormError style={styles.formItemError} name="username" />
              </div>
            </div>
          </FormBinderWrapper>
        </Dialog>
      </Container>
    );
  }

  // 向后台获取settingsData数据 get http://localhost:9080/users/current
  componentDidMount() {
    this.props.getSettingsData();
  }
}

const styles = {
  header: {
    display: 'flex',
    justifyContent: 'space-between',
  },
  title: {
    fontSize: 20,
    margin: 0,
    paddingBottom: 20,
  },
  infoRow: {
    padding: '16px 0',
    display: 'flex',
    borderBottom: '1px solid #f6f6f6',
  },
  infoLabel: {
    flex: '0 0 100px',
    color: '#999',
  },
  infoDetail: {},

  formItem: {
    marginBottom: '20px',
    display: 'flex',
    alignItems: 'center',
  },
  formItemLabel: {
    width: '70px',
    mariginRight: '10px',
    display: 'inline-block',
    textAlign: 'right',
  },
  formItemError: {
    marginLeft: '10px',
  },
};

const mapState = (state) => ({
  dialogVisible: state.getIn(['settings', 'dialogVisible']),
  settingsData: state.getIn(['settings', 'settingsData']).toJS()
});

const mapDispatch = (dispatch) => ({
  getSettingsData() {
    dispatch(actionCreators.getSettingsData());
  },
  handleOpenEditPanel() {
    dispatch(actionCreators.handleOpenEditPanel());
  },
  handleCloseEditPanel() {
    dispatch(actionCreators.handleCloseEditPanel());
  },
  submitEdit(data) {
    console.log(data);
    dispatch(actionCreators.submitEdit(data));
  }
});

export default connect(mapState, mapDispatch)(AccountPanel);